// pages/activity-info/activity-info.js
const app = getApp();
const request = require('../../utils/request.js');
const config = require('../../utils/config');
const util = require('../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    colorTheme: app.globalData.colorTheme,
    activityId: -1,
    activityInfo: {}
  },

  /**
   * 获取活动信息
   */
  getActivityInfo(){
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + 'activity/detail/' + this.data.activityId;
    wx.showLoading({
      title: '加载ing'
    });
    request.requestGetApi(url, token, {}, 'application/json').then(res=>{
      res.data.actStatus = util.computedTimeStatus(res.data.startTime, res.data.endTime);
      if(res.status === config.STATUS_OK){
        this.setData({
          activityInfo: res.data
        })
      }
    }).catch(err=>{
      app.failFun(err);
    }).finally((res) => {
      app.completeFun(res);
    });
  },

  /**
   * 取消或收藏活动
   */
  collectOrCancelActivity(){
    if(!app.checkedUserLoading()){
      return;
    }
    let that = this;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL;
    let activityInfo = that.data.activityInfo;
    if(activityInfo.collect){
      url += 'activity/collect_cancel/' + this.data.activityId;
    }else{
      url += 'activity/collect/' + this.data.activityId;
    }
    activityInfo.collect = !activityInfo.collect;
    request.requestPostApi(url, token, {}, 'application/json').then(res=>{
      if(res.status === config.STATUS_OK){
        that.setData({
          activityInfo
        });
        wx.showToast({
          title: res.message,
          icon: 'success',
          duration: 1500,
        });
      }
    }).catch(err=>{
      app.failFun(err);
    })
  },

  /**
   * 取消或预约活动
   */
  appointmentActivities(){
    if(!app.checkedUserLoading()){
      return;
    }
    let that = this;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL;
    let activityInfo = that.data.activityInfo;
    if(activityInfo.appointment){
      url += 'activity/cancelAppointment/' + this.data.activityId;
      activityInfo.appointmentCount--;
    }else{
      url += 'activity/appointment/' + this.data.activityId;
      activityInfo.appointmentCount++;
    }
    activityInfo.appointment = !activityInfo.appointment;
    request.requestPostApi(url, token, {}, 'application/json').then(res=>{
      if(res.status === config.STATUS_OK){
        that.setData({
          activityInfo
        });
        wx.showToast({
          title: res.message,
          icon: 'success',
          duration: 1500,
        });
      }
    }).catch(err=>{
      app.failFun(err);
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      activityId: options.id
    });
    this.getActivityInfo();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})